import style from './style.module.less'
import {
  EditOutlined,
  ExportOutlined,
  HomeOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { Avatar, message } from 'antd'
import React, { useEffect, useState } from 'react'
import * as api from '../../services/api'
import { useHistory } from 'react-router-dom'

export default function Header(props: any) {
  let token: string = props.token

  const history = useHistory()

  const [imgKey, setImgKey] = useState<string>('')
  const [url, setUrl] = useState<string>('')
  const [nickname, setNickname] = useState<string>('')

  useEffect(() => {
    getUserInfo()
  }, [])

  useEffect(() => {
    getImg()
  }, [imgKey])

  async function getImg() {
    try {
      if (imgKey.length > 0) {
        let res = await api.downloadFile(imgKey)
        setUrl((window.URL || window.webkitURL).createObjectURL(res.data))
      }
    } catch (e) {
      throw e
    }
  }

  async function getUserInfo() {
    try {
      let res = await api.getUserInfo(token)
      if (res.data.stat === 'ok') {
        setImgKey(res.data.data.avatar)
        if (res.data.data.nickname === '') {
          setNickname(res.data.data.account)
        } else {
          setNickname(res.data.data.nickname)
        }
      } else {
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  async function logout() {
    try {
      let res = await api.logout(token)
      if (res.data.stat === 'ok') {
        message.destroy()
        message.success('退出登录')
        localStorage.removeItem('md')
        localStorage.removeItem('avatar')
        history.push('/login')
      } else {
        message.destroy()
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  function jumpCreate() {
    history.push(`/create/${token}`)
  }

  function jumpPersonal() {
    history.push(`/personal/${token}`)
  }

  function jumpMain() {
    history.push(`/main/${token}`)
  }

  return (
    <div className={style.header}>
      <span className={style.headerBack} onClick={() => jumpMain()}>
        <HomeOutlined className={style.headerIcon} />
        首页
      </span>
      <span className={style.headerTitle}>
        木易&nbsp;&nbsp;&nbsp;&nbsp;
        <span onClick={jumpCreate}>
          <EditOutlined className={style.headerIcon} />
          开始你的创作
        </span>
      </span>
      <span className={style.headerPeople}>
        <span className={style.headerUser}>{nickname}</span>
        <div onClick={jumpPersonal}>
          <Avatar className={style.headerImg} src={`${url}`} alt={'error'} />
        </div>
      </span>
      <span className={style.headerPerson} onClick={() => jumpPersonal()}>
        <UserOutlined className={style.headerIcon} />
        个人中心
      </span>
      <span className={style.headerLogout} onClick={() => logout()}>
        退出登录
        <ExportOutlined className={style.headerIcon} />
      </span>
    </div>
  )
}
